package com.android.dx.youzan.meiye;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.dx.youzan.app.App;
import com.android.dx.youzan.app.Cookies;
import com.android.dx.youzan.meiye.model.Address;
import com.android.dx.youzan.meiye.model.CardGoods;
import com.android.dx.youzan.meiye.model.ProductGoods;
import com.lg.meng.utils.ThreadUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Author: Ligang
 * Date: 2020/01/10
 * Description:
 */
public class ProductMain {
    static OkHttpClient okHttpClient = new OkHttpClient();

    public static void main(String[] args) {
        ThreadUtils.runOnThread(() -> {
            Cookies cookies = App.getCookie();
            String cookie = cookies.getCookie(); //cookie 像京东拼购一样，买手cookie由app上传
            String _csrf = cookies.get_csrf(); //cookie中的一个值
            String kdtId = "43990976"; //店铺的属性
            String deptId = "43993058"; //店铺的属性
//            createUserAddress(cookie, _csrf, kdtId, deptId, "桐梓林", "周杰伦" + (int) (Math.random() * 100), "17711322850",
//                    "四川省", "成都市", "武侯区", "510107");

            log("开始查询店铺的产品列表");
            listProductByBuyer(cookie, _csrf, kdtId, deptId);
        });
    }

    /**
     * 产品列表
     *
     * @param cookie
     * @param _csrf
     * @param kdtId
     * @param deptId
     */
    private static void listProductByBuyer(String cookie, String _csrf, String kdtId, String deptId) {
        String url = "https://mei1cxndddbnxeobh.youzan.com/api/h5/free/mei/product/listProductByBuyer?_csrf=" + _csrf;
        String bodyJson = "{\n" +
                "\t\"json\": \"{\\\"desc\\\":1,\\\"keyword\\\":\\\"\\\",\\\"orderByType\\\":3,\\\"pageNo\\\":1" +
                ",\\\"pageSize\\\":20,\\\"tagId\\\":0,\\\"yzUid\\\":\\\"488346362\\\",\\\"kdtId\\\":\\\"" + kdtId + "\\\"" +
                ",\\\"deptId\\\":\\\"" + deptId + "\\\"}\"\n" +
                "}";

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; Charset=utf-8"), bodyJson);
        Request request = new Request.Builder().url(url).post(requestBody)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cookie", cookie)
                .build();
        String string = "";
        try {
            Response response = okHttpClient.newCall(request).execute();
            string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code") == 10000) {
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                log("查询到" + jsonArray.size() + "个产品");
                int goodsIndex = (int) (Math.random() * jsonArray.size());
                JSONObject itemObj = jsonArray.getJSONObject(goodsIndex);
                ProductGoods goods = JSON.parseObject(itemObj.toJSONString(), ProductGoods.class);
                log("随机选择第" + (goodsIndex + 1) + "个产品购买");
                log("开始获取买家地址列表");
                listAddressByUserId(cookie, _csrf, kdtId, deptId, goods);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取买家地址列表
     */
    private static void listAddressByUserId(String cookie, String _csrf, String kdtId, String deptId, ProductGoods goods) {
        String url = "https://cashier.youzan.com/pay/mei/api/mei/uicAddress/listAddressByUserId?_csrf=" + _csrf + "&json="
                + "{\"kdtId\":\"" + kdtId + "\",\"deptId\":\"" + deptId + "\"}";
        Request request = new Request.Builder()
                .get().url(url)
                .addHeader("Cookie", cookie)
                .build();
        try {
            Response execute = okHttpClient.newCall(request).execute();
            String string = execute.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getIntValue("code") == 10000) {
                List<Address> addressList = JSON.parseArray(jsonObject.getJSONArray("data").toJSONString(), Address.class);
                if (addressList == null || addressList.size() == 0) {
                    log("地址列表为空");
                    return;
                }
                int addressId = addressList.get(0).getId();
                orderBuyerSave(cookie, _csrf, kdtId, deptId, goods, addressId);
            } else {
                log("获取地址列表失败：" + jsonObject.getString("message"));
                log("获取地址列表返回" + string);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("获取地址列表失败：" + e.getMessage());
        }
    }

    private static void orderBuyerSave(String cookie, String _csrf, String kdtId, String deptId, ProductGoods goods, int addressId) {
        String url = "https://cashier.youzan.com/pay/mei/api/mei/order/buyer/save?_csrf=" + _csrf;
        String bodyJson = "{\n" +
                "\t\"json\": \"{\\\"buyer\\\":{\\\"addressId\\\":" + addressId + "},\\\"buyerMemo\\\":\\\"\\\"," +
                "\\\"type\\\":8,\\\"orderItems\\\":[{\\\"itemType\\\":8,\\\"itemId\\\":" + goods.getId()
                + ",\\\"goodsId\\\":" + goods.getGoodsId() + ",\\\"skuId\\\":" + goods.getDefaultGoodsStock().getSkuId()
                + ",\\\"originPrice\\\":" + goods.getPrice() + ",\\\"num\\\":1,\\\"realPay\\\":" + goods.getPrice() + "}]" +
                ",\\\"kdtId\\\":\\\"" + kdtId + "\\\",\\\"deptId\\\":\\\"" + deptId + "\\\"}\"\n" +
                "}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; Charset=utf-8"), bodyJson);
        Request request = new Request.Builder().url(url).post(requestBody)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cookie", cookie)
                .build();
        String string = "";
        try {
            Response response = okHttpClient.newCall(request).execute();
            string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getIntValue("code") == 200) {
                String orderNo = jsonObject.getJSONObject("data").getString("orderNo");
                log("orderBuyerSave成功:" + orderNo);
                direct_pay(cookie, _csrf, kdtId, deptId, orderNo);
            } else {
                log("orderBuyerSave失败：" + jsonObject.getString("message"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 加入购物车
     */
    @Deprecated
    private static void addToCart(String cookie, String _csrf, String kdtId, String deptId, ProductGoods goods) {
        String url = "https://mei1cxndddbnxeobh.youzan.com/api/h5/mei/cart/buyer/add?_csrf=" + _csrf + "&json="
                + "{\"nameList\":[],\"nameVOList\":[],\"skuId\":" + goods.getDefaultGoodsStock().getSkuId() + ",\"code\":\""
                + goods.getDefaultGoodsStock().getCode() + "\",\"price\":" + goods.getPrice() + ",\"costPrice\":"
                + goods.getDefaultGoodsStock().getCostPrice() + ",\"stockNum\":" + goods.getDefaultGoodsStock().getStockNum() + "," +
                "\"totalSoldNum\":" + goods.getDefaultGoodsStock().getTotalSoldNum() + ",\"goodsId\":" + goods.getDefaultGoodsStock().getGoodsId()
                + ",\"num\":1,\"itemId\":" + goods.getGoodsId() + ",\"itemType\":8,\"kdtId\":\"" + kdtId + "\",\"deptId\":\"" + deptId + "\"}";
        Request request = new Request.Builder()
                .get().url(url)
                .addHeader("Cookie", cookie)
                .build();

        try {
            Response execute = okHttpClient.newCall(request).execute();
            String string = execute.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getIntValue("code") == 200) {
                String itemNo = jsonObject.getJSONObject("data").getString("itemNo");//C20011017132412180208
                log("加入购物车成功，itemNo:" + itemNo);
                prepareOrder(cookie, _csrf, kdtId, deptId, itemNo);
            } else {
                log("加入购物车失败：" + jsonObject.getString("message"));
                log("加入购物车返回" + string);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("加入购物车失败：" + e.getMessage());
        }

    }

    /**
     * 准备购买
     */
    @Deprecated
    private static void prepareOrder(String cookie, String _csrf, String kdtId, String deptId, String itemNo) {
        String url = "https://mei1cxndddbnxeobh.youzan.com/api/h5/mei/cart/buyer/prepare_order?_csrf=" + _csrf + "&json="
                + "{\"itemNos\":[\"" + itemNo + "\"],\"kdtId\":\"" + kdtId + "\",\"deptId\":\"" + deptId + "\"}";
        Request request = new Request.Builder()
                .get().url(url)
                .addHeader("Cookie", cookie)
                .build();

        try {
            Response execute = okHttpClient.newCall(request).execute();
            String string = execute.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getIntValue("code") == 200) {
                log("prepareOrder成功");
                direct_pay(cookie, _csrf, kdtId, deptId, itemNo);
            } else {
                log("prepareOrder失败：" + jsonObject.getString("message"));
                log("prepareOrder返回" + string);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("prepareOrder失败：" + e.getMessage());
        }
    }

    private static void direct_pay(String cookie, String _csrf, String kdtId, String deptId, String orderNo) {
        String url = "https://cashier.youzan.com/pay/mei/api/mei/pay/buyer/direct_pay?_csrf=" + _csrf + "&json="
                + "{\"orderNo\":\"" + orderNo + "\",\"channelType\":4,\"accountNo\":\"\",\"kdtId\":\"" + kdtId + "\",\"deptId\":\"" + deptId + "\"}";
        Request request = new Request.Builder()
                .get().url(url)
                .addHeader("Cookie", cookie)
                .build();
        try {
            Response execute = okHttpClient.newCall(request).execute();
            String string = execute.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getIntValue("code") == 200) {
                log("direct_pay成功，开始获取支付链接");
                ServiceMain.拿支付链接(jsonObject);
            } else {
                log("direct_pay失败：" + jsonObject.getString("message"));
                log("direct_pay返回" + string);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("direct_pay失败：" + e.getMessage());
        }
    }

    /**
     * @param cookie
     * @param _csrf
     * @param kdtId
     * @param deptId
     * @param address      详细地址
     * @param userNickName 收货人姓名
     * @param phone        收货人电话
     * @param province     四川省
     * @param city         成都市
     * @param county       武侯区
     * @param areaCode     对应county的id
     *                     城市对应json：    http://39.100.76.8/app/ppx/youzanaddress.json
     */
    private static void createUserAddress(String cookie, String _csrf, String kdtId, String deptId,
                                          String address, String userNickName, String phone,
                                          String province, String city, String county, String areaCode) {
        String url = "https://cashier.youzan.com/pay/mei/api/mei/uicAddress/createUserAddress?_csrf=" + _csrf + "&json="
                + "{\"areaCode\":" + areaCode + ",\"address\":\"" + address + "\",\"userNickName\":\"" + userNickName + "\"" +
                ",\"phone\":" + phone + ",\"province\":\"" + province + "\",\"city\":\"" + city + "\"" +
                ",\"county\":\"" + county + "\",\"kdtId\":\"" + kdtId + "\",\"deptId\":\"" + deptId + "\"}";
        Request request = new Request.Builder()
                .get().url(url)
                .addHeader("Cookie", cookie)
                .build();
        try {
            Response execute = okHttpClient.newCall(request).execute();
            String string = execute.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getIntValue("code") == 10000) {
                log("创建地址成功，地址id:" + jsonObject.getIntValue("data"));
            } else {
                log("创建地址失败：" + jsonObject.getString("message"));
                log("创建地址返回" + string);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("创建地址失败：" + e.getMessage());
        }
    }

    private static void log(Object obj) {
        Log.e(TAG, obj + "");
        EventBus.getDefault().post(obj.toString());
    }

    private static final String TAG = "youzanmeiye";
}
